package com.bizzard.user.service.impl;

import com.bizzard.basic.constant.VerifyConstants;
import com.bizzard.basic.exception.BusinessException;
import com.bizzard.basic.util.MD5Utils;
import com.bizzard.basic.util.StrUtils;
import com.bizzard.user.domain.Logininfo;
import com.bizzard.user.domain.User;
import com.bizzard.user.dto.UserDto;
import com.bizzard.user.mapper.LogininfoMapper;
import com.bizzard.user.mapper.UserMapper;
import com.bizzard.user.service.IUserService;
import com.bizzard.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;



    @Override
    public void add(User user) {
        super.add(user);
    }

    @Override
    public void del(Long id) {
        //获取登录信息id
        Long logininfoId = userMapper.loadById(id).getLogininfoId();
        //删除登录信息对象
        logininfoMapper.remove(logininfoId);
        //删除用户信息
        super.del(id);
    }

    @Override
    public void update(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //用户user：createtime和logininfo_id不能修改

        //获取登录信息id
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfoId();
        //登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        super.update(user);
    }

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //1.校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 密码一致校验
        if(!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致");
        }

        //3.校验 - 验证码是否过期 :  9527:441122222
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_PREFIX + phone);
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码失效");
        }
        //4.校验 - 验证码是否正确
        if(!redisPhoneCode.toString().split(":")[0].equalsIgnoreCase(phoneCode)){
            throw new BusinessException("手机验证码错误");
        }

        //5.添加 - t_logininfo信息
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //6.添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        User user1 = userMapper.loadByEmail(email);

        // 判断邮箱是否注册过
        if(user1 != null){
            throw new BusinessException("你已经注册，请直接登录，忘记密码请联系管理员!!!");
        }
        // 空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat) ) {
            throw new BusinessException("数据不能为空");
        }
        // 密码一致验证,去掉前后空格
        if(!password.trim().equals(passwordRepeat.trim())) {
            throw new BusinessException("前后密码不一致");
        }
        //5.添加 - t_logininfo信息
        User user = userDto3User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //6.添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

        // 3.发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        // 设置发送方
        helper.setFrom("18160016785@163.com");
        // 设置主题
        helper.setSubject("店铺激活邮件");
        // 设置内容
        helper.setText("邮箱注册成功",true);
        // helper.setTo(employee.getEmail());
        helper.setTo(email);
        // 发送
        javaMailSender.send(mimeMessage);
    }



    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //设置为用户
        logininfo.setType(1);
        return logininfo;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private User userDto3User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }

}
